package com.czy.owner.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.owner.R;
import com.czy.owner.api.LuckDrawApi;
import com.czy.owner.api.LuckDrawSuccessApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.LuckDrawModel;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.ShareEvent;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.ui.login.LoginActivity;
import com.czy.owner.utils.AssetsFileUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.ShareUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.widget.UniversalDialog;

import butterknife.BindView;
import butterknife.ButterKnife;

//显示静态页的界面
public class LuckDrawWebviewActivity extends BaseActivity {

    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    private WebViewRequestParam webViewRequestParam;
    private int myType = 0;
    MenuItem itemCollect;
    private String imgUrl = "http://img.mp.itc.cn/upload/20160910/c5f96a807dca41d1b889bdd41dd27e1b_th.jpeg";
    private LuckDrawModel luckDrawModel;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initInjector() {
        RxBus.getDefault().register(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_goods_detail, menu);
        itemCollect = menu.findItem(R.id.img_collection);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.img_share:
                if (StringUtils.isEmpty(UserHelper.getInstance().getSession(this))) {
                    new UniversalDialog(this).builder()
                            .setCancelable(false)
                            .setMsg("你还未登录，现在去登录?")
                            .setPositiveButton("去登录", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(LuckDrawWebviewActivity.this, LoginActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, false));

                                }
                            }).setNegativeButton("不登录", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                        }
                    }).show();
                    return super.onOptionsItemSelected(item);
                }
                getShare();
                break;


        }
        return super.onOptionsItemSelected(item);
    }

    /*接受事件*/
    @Subscribe(code = Constants.GOODS_SHARE_CODE, threadMode = ThreadMode.MAIN)
    public void event(ShareEvent shareEvent) {
        if ("1".equals(shareEvent.getType())) {
            PhoneUtils.ShowToastMessage(LuckDrawWebviewActivity.this, "分享成功");
            getShareSuccess(shareEvent);
        } else if ("2".equals(shareEvent.getType())) {
            PhoneUtils.ShowToastMessage(LuckDrawWebviewActivity.this, "分享失败");
        } else if ("3".equals(shareEvent.getType())) {
            PhoneUtils.ShowToastMessage(LuckDrawWebviewActivity.this, "分享取消");
        }

    }

    //获取抽取次数
    public void getShareSuccess(ShareEvent shareEvent) {

        LuckDrawSuccessApi luckDrawSuccessApi = new LuckDrawSuccessApi(new HttpOnNextListener<Object>() {
            @Override
            public void onNext(Object result) {
//                PhoneUtils.ShowToastMessage(LuckDrawWebviewActivity.this, "获得抽奖机会");
                if (webViewRequestParam.getRequestMethod() == WebViewRequestParam.REQUEST_POST) {
                    webview.postUrl(webViewRequestParam.getUrl(), webViewRequestParam.getParams().getBytes());
                } else {
                    MyLog.e("yang", "webViewRequestParam==" + webViewRequestParam.getUrl());
                    webview.loadUrl(webViewRequestParam.getUrl() + "?" + webViewRequestParam.getParams().getBytes());
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                PhoneUtils.ShowToastMessage(LuckDrawWebviewActivity.this, e.getMessage());
            }
        }, LuckDrawWebviewActivity.this);
        luckDrawSuccessApi.setSession(UserHelper.getInstance().getSession(this));
        luckDrawSuccessApi.setPlatform(shareEvent.getPlatform());
        luckDrawSuccessApi.setGoodsActivityId(luckDrawModel.getGoodsActivityId());
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(luckDrawSuccessApi);
    }

    //获取三方分享内容
    public void getShare() {

        LuckDrawApi luckDrawApi = new LuckDrawApi(new HttpOnNextListener<LuckDrawModel>() {
            @Override
            public void onNext(LuckDrawModel result) {
                luckDrawModel = result;
                //调用分享
                if (TextUtils.isEmpty(result.getShareLogo())) {
                    try {
                        AssetsFileUtils.getImageFromAssetsFile(LuckDrawWebviewActivity.this, "owner_share_icon.png");
                    } catch (Exception e) {

                    }
                }
                ShareUtils.showShare(LuckDrawWebviewActivity.this, null, false,
                        Constants.APP_API_BASE + Constants.OWN_SHOP_LUCKDRAW + "?flag=true", PhoneUtils.delHTMLTag(StringUtils.isEmpty(result.getShareTitle()) ? "袋鼠车管家" : result.getShareTitle()),
                        PhoneUtils.delHTMLTag(StringUtils.isEmpty(result.getShareContent()) ? "把爱车装进口袋" : result.getShareContent()),
                        result.getShareLogo(), Constants.APP_API_BASE + Constants.OWN_SHOP_LUCKDRAW + "?flag=true");
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(LuckDrawWebviewActivity.this, e.getMessage());
            }
        }, LuckDrawWebviewActivity.this);
        luckDrawApi.setSession(UserHelper.getInstance().getSession(this));
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(luckDrawApi);
    }

    @Override
    protected void initViews() {
        myProgressBar.setVisibility(View.GONE);
        if (getIntent().getExtras() == null) {
            Toast.makeText(this, "数据异常", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        webViewRequestParam = (WebViewRequestParam) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
        if (webViewRequestParam != null) {
            toolbarTitle.setText(webViewRequestParam.getTitle());
        }
        webview.setWebViewClient(new MyWebViewClient());

        WebSettings ws = webview.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setUseWideViewPort(false);
        ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        ws.setDomStorageEnabled(true);
        ws.setUseWideViewPort(true);// 关键点

        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        ws.setDisplayZoomControls(false);

//        ws.setJavaScriptEnabled(true); // 设置支持javascript脚本
        ws.setAllowFileAccess(true); // 允许访问文件
        ws.setBuiltInZoomControls(true); // 设置显示缩放按钮
        ws.setSupportZoom(true); // 支持缩放
        if (webViewRequestParam.getRequestMethod() == WebViewRequestParam.REQUEST_POST) {
            webview.postUrl(webViewRequestParam.getUrl(), webViewRequestParam.getParams().getBytes());

        } else {
            MyLog.e("yang", "webViewRequestParam==" + webViewRequestParam.getUrl());
            webview.loadUrl(webViewRequestParam.getUrl() + "?" + webViewRequestParam.getParams().getBytes());
        }

//        http://118.178.188.69/own/shop/priceRatio/info?infoId=2686
//        http://118.178.188.69/pub/goodsView?goodsId=1053

        // http://118.178.188.69/own/shop/priceRatio?joinType=0&goodsActivityId=339  立即参与
        //joinType=0 商品列表  joinType=1 热门商城分类


        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                MyLog.e("yang--", url);

                if (url.toString().contains("own/login")) {
                    startActivity(new Intent(LuckDrawWebviewActivity.this, LoginActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, false));
                    return true;
                } else if (url.toString().contains("/own/share")) {
                    getShare();
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

//            @Override
//            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//                MyLog.e("yang--", request.getUrl().toString());
//                String mPattern = "1212";
//                if (request.getUrl().toString().contains("own/login")) {
//                    startActivity(new Intent(LuckDrawWebviewActivity.this, LoginActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, false));
//
//                }else if (request.getUrl().toString().contains("/own/share")){
//                    getShare();
//                    return null;
//                }
//                return super.shouldInterceptRequest(view, request);
//            }


        });

        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (myProgressBar != null) {
                        myProgressBar.setVisibility(View.GONE);
                    }
                    if (myProgressBar != null) {
                        myProgressBar.setVisibility(View.GONE);
                    }
                } else {
                    myProgressBar.setVisibility(View.VISIBLE);
                    myProgressBar.setProgress(newProgress);

                }
            }

        });

    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (webViewRequestParam.getRequestMethod() == WebViewRequestParam.REQUEST_POST) {
                view.postUrl(url, webViewRequestParam.getParams().getBytes());
            } else {
                view.loadUrl(url + "?" + webViewRequestParam.getParams().getBytes());
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            getToolbarTitle().setText(view.getTitle());
            mLoadView.CancleLoadView();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            getToolbarTitle().setText("");
            mLoadView.ShowLoadView();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webview.destroy();
        RxBus.getDefault().unRegister(this);
    }
}
